import utils from '@/utils';
import { compile } from 'vue';
import { Utils } from './utils';
import { log } from 'console';
// 标记登录是否过期
let isLoginExpired = false;
/**
 * 判断是否登录过期
 * @param res
 * @returns
 */
const isLoginExpiredFn = (res: any) => {
  let data = res?.data && res?.data[0] ? res?.data[0] : [];
  if (data.length == 0) data = res?.data ? [res?.data] : [];
  if (data.length > 0 && data[0]?.Result?.ResponseStatus?.IsSuccess == false) {
    const d = data[0]?.Result?.ResponseStatus;
    if (d?.MsgCode == 1) {
      isLoginExpired = true;
      Utils.showErr(d.Errors[0]?.Message || '', () => {
        uni.clearStorageSync();
        utils.reLaunch('home/index');
        isLoginExpired = false;
      });
      return false;
    }
  }
  return true;
};
// 设置一个定时器
let timer: any = null;
const request =async (reqObj: any) => {
  const { url,method = 'GET',data = {},contentType = 'json',dataType = 'json',isReturnRes = false, showLoad = false } = reqObj;
  const say = uniCloud.importObject("k3cloud",{
	  customUI:!showLoad
  })
  const currentServerUrl = 'http://120.79.53.7/k3cloud';
  // 如果定时器存在，清除定时器
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }

  if(say ){
	  if (isLoginExpired) return;
	  try {
		  const headers = {
		    'kdservice-sessionid': utils.getStorage('KDSVCSessionId') || '',
		  };
		// 调用云函数 
	  	const res =await say.sendRequest
	  	 ({
	  		 url:currentServerUrl + url,
	  		 data,
			 method,
	  		 contentType,
	  		 dataType,
			 headers
	  	 })
		 // console.log(res,'sendRequest=res');
	  	 if(res){
	  		 // 直接放回数据
	  		 if(isReturnRes)return res.data
			 // 检查是否登录过期
	  		 if (!isLoginExpiredFn(res)) return;
	  		  return res.data
	  	}
		 utils.hideLoading()
	  } catch (error) {
	  	 utils.hideLoading()
	  }
	  
	}
};

export default request;
